//
//  StatusRefresh.swift
//  新浪微博01
//
//  Created by 李国伟 on 15/12/14.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit
let WBoffset:CGFloat = -60
var flag = false
class WBRefreshControl: UIRefreshControl {
    
   //重写构造方法
    override init() {
        super.init()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }

    //开始动画
    override func beginRefreshing() {
        super.beginRefreshing()
        startAnimation()
    }
    
    //结束动画
    override func endRefreshing() {
        super.endRefreshing()
        stopAnimation()
    }
    
    //kvo回调
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //如果往上滑就不监听
        if frame.origin.y > 0{
            return
        }
        
        if frame.origin.y < WBoffset && !flag {
            startToprotate()
            flag = true
        }else if frame.origin.y > WBoffset && flag {
            startToprotate()
            flag = false
        }
    }
    
     //UINib和 loadNibName的区别
    private lazy var refreshView: StatusRefreshView = {
       
        let nib = UINib(nibName: "StatusRefresh", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).first as! StatusRefreshView
    }()
    
    private func setupUI(){
        addSubview(refreshView)
        
        //冲xib加载的view必须设置大小才能设置约束
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    //销毁监KVO
    deinit{
        removeObserver(self, forKeyPath: "frame")
    }
    
    //开始动画
    private func startToprotate(){
     //ios动画的特点，就近原则
        refreshView.topView.hidden = false
        let rotate = flag ? CGFloat(M_PI) + 0.00001 : CGFloat(M_PI) - 0.00001
        UIView.animateWithDuration(0.5) { () -> Void in
            self.refreshView.rotateImage.transform = CGAffineTransformRotate(self.refreshView.rotateImage.transform, CGFloat(rotate))
        }
    }
    
    //设置加载动画
    private func startAnimation(){
        refreshView.topView.hidden = true
        let key = "transform.rotation"
        if (refreshView.arrawImage.layer.animationForKey(key) != nil){
            return
        }
        
        let anim = CABasicAnimation()
        anim.duration = 2
        anim.keyPath = key
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.removedOnCompletion = false
        
        refreshView.arrawImage.layer.addAnimation(anim, forKey: key)
    }
    
   //取消加载动画
    private func stopAnimation(){
        refreshView.arrawImage.layer.removeAllAnimations()
    }
}
